package com.imooc.service.impl;

import com.imooc.es.pojo.Items;
import com.imooc.service.ItemsESService;
import com.imooc.utils.PagedGridResult;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: ItemsESServiceImpl
 * @Description:
 * @Author: zhangjin
 * @Date: 2022/10/27
 */
@Service
public class ItemsESServiceImpl implements ItemsESService {

    @Resource
    private ElasticsearchTemplate esTemplate;

    @Override
    public PagedGridResult searchItems(String keywords, String sort, Integer page, Integer pageSize) {
        // 这里使用自定义标签font作为高亮的方式不太好，因为前端可能会自定义额外的样式作为高亮，这个标签可以和前端沟通，也可以使用默认的标签<em>
//        String preTag = "<font color='red'>";
//        String postTag = "</font>";
        Pageable pageable = PageRequest.of(page - 1, pageSize); // 因为es的from标签是从0开始的，所以page需要-1

        SortBuilder<FieldSortBuilder> sortBuilder = null;
        // 销售量排序
        if ("c".equals(sort)) {
            sortBuilder = new FieldSortBuilder("sellCounts").order(SortOrder.DESC);
            // 价格排序
        } else if ("p".equals(sort)) {
            sortBuilder = new FieldSortBuilder("price").order(SortOrder.ASC);
            // 默认商品名排序
        } else {
            sortBuilder = new FieldSortBuilder("itemName.keyword").order(SortOrder.ASC); // 注意text属性需要根据keyword进行排序
        }

        String itemNameField = "itemName";

        SearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery(itemNameField, keywords))
                .withHighlightFields(new HighlightBuilder.Field(itemNameField)
//                        .preTags(preTag)
//                        .postTags(postTag)
                )
                .withSort(sortBuilder)
                .withPageable(pageable)
                .build();
        AggregatedPage<Items> pageItems = esTemplate.queryForPage(query, Items.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> aClass, Pageable pageable) {
                List<Items> itemsListHighlight = new ArrayList<>();

                SearchHits hits = response.getHits();
                for (SearchHit hit : hits) {
                    Items items = new Items();
                    String itemId = hit.getSourceAsMap().get("itemId").toString();
                    items.setItemId(itemId);

                    HighlightField highlightField = hit.getHighlightFields().get(itemNameField);
                    String itemName = highlightField.getFragments()[0].toString();
                    items.setItemName(itemName);

                    String imgUrl = hit.getSourceAsMap().get("imgUrl").toString();
                    items.setImgUrl(imgUrl);

                    Integer price = Integer.valueOf(hit.getSourceAsMap().get("price").toString());
                    items.setPrice(price);

                    Integer sellCounts = Integer.valueOf(hit.getSourceAsMap().get("sellCounts").toString());
                    items.setSellCounts(sellCounts);

                    itemsListHighlight.add(items);
                }
                return new AggregatedPageImpl<>((List<T>)itemsListHighlight, pageable, hits.totalHits);
            }
        });

        PagedGridResult gridResult = new PagedGridResult();
        gridResult.setRows(pageItems.getContent());
        gridResult.setPage(page);
        gridResult.setTotal(pageItems.getTotalPages());
        gridResult.setRecords(pageItems.getTotalElements());
        return gridResult;
    }

}
